import type {ProFormInstance} from '@ant-design/pro-components';
import {
  ProForm,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  StepsForm
} from '@ant-design/pro-components';
import {message} from 'antd';
import React, {useEffect, useRef, useState} from 'react';;
import {listProjectUsingPost} from "@/services/easyapi/eProject";
import {ProFormDependency} from "@ant-design/pro-form";
import {
  getAllDatabasesUsingPost,
  listDatasourceByProjectIdUsingPost,
} from "@/services/easyapi/eDatasource";
import {configInterfaceUsingPost, generateInterfaceUsingPost} from "@/services/easyapi/eApiManage";
import SqlFunctionEditor from "@/pages/ApiManage/components/SqlFunctionEditor";
import ConfigSqlInputParam from "@/pages/ApiManage/components/ConfigSqlInputParam";


export type Props={
  visible: boolean
  setVisible: (visible: boolean) => void
  selectedForm:string,
  setSelectedForm:(selectedForm:string) => void,
}


const AddConfigSqlInterface: React.FC<Props> = (props) => {
  const{setVisible,setSelectedForm} = props;
  const formRef = useRef<ProFormInstance>();
  const[datasourceId, setDatasourceId] = useState<number>(0)
  const[databaseName, setDatabaseName] = useState<string>('')
  const[databaseList, setDatabaseList] = useState<string[]>([])
  const[projectId, setProjectId] = useState<number>(0)
  const[datasourceList, setDatasourceList] = useState<string[]>([])
  const[sql,setSql] = useState<string>('')
  const[configInputParam,setConfigInputParams] = useState<API.ConfigInputParam[]>([])
  useEffect(() => {
    if (projectId!==0){
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      fetchDatasourceList(projectId)
    }
  }, [projectId]);

  useEffect(() => {
    if (datasourceId!==0 && datasourceId!==undefined && datasourceId!==null){

      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      fetchDatabaseList(datasourceId)
    }
  }, [datasourceId]);

  //获取项目列表
  const listProjectVo = async (projectName: string) => {
    const res = await listProjectUsingPost({});
    if (res.code === 200) {
      //@ts-ignore
      return res.data.map((project) => ({
        label: project.projectName, // 使用项目名称作为选项的标签
        value: project.id,   // 使用项目ID作为选项的值
      }));
    } else {
      return []
    }
  }


  //获取数据源列表
  const fetchDatasourceList = async (projectId:number)=>{
    const res = await listDatasourceByProjectIdUsingPost({
      projectId:projectId
    });
    if (res.code===200){
      //@ts-ignore
      const datasourceListMap = res.data.map((datasource)=>({
        label: datasource.dataName,
        value: datasource.id,
      }))
      //@ts-ignore
      setDatasourceList(datasourceListMap)
    }else{
      message.error(res.msg);
      setDatasourceList([])
    }
  }

  //获取数据库
  const fetchDatabaseList = async (datasourceId:number)=>{
    const res = await  getAllDatabasesUsingPost({
      id: datasourceId,
    });
    if (res.code===200){
      //@ts-ignore
      const databases = res.data.map((item)=>({
        label: item,
        value: item,
      }))
      //@ts-ignore
      setDatabaseList(databases)
    } else{
      message.error(res.msg);
      setDatabaseList([])
    }
  }



  return (
    <>
      <StepsForm<{
        name: string
      }>
        formRef={formRef}
        onFinish={async (values) => {
          const res = await configInterfaceUsingPost({
            ...values,
            configSql:sql,
            configInputParams: configInputParam
          })
          if (res.code===200){
            message.success('添加成功')
            setSelectedForm('')
            setSql('')
            setConfigInputParams([])
            setVisible(false)
          }else {
            message.error(res.msg)
          }

        }}
      >
        {/* ----------------------------------------------step one-------------------------------------------------------------*/}
        <StepsForm.StepForm
          title={"基本属性"}
          name={"generateBase"} >
          <ProFormSelect
            label={"请选择项目"}
            tooltip={"项目引用的数据源才能够配置参数"}
            name={"projectId"}
            request={async () => {
              return listProjectVo('');
            }}
            onChange={(value)=>{
              console.log("projectId = >",value)
              //@ts-ignore
              setProjectId(value)
            }}
            rules={[
              {required: true, message: '请选择所属项目'}
            ]}
          />
          <h4 style={{
            fontSize: '15px',
            fontWeight: 'bold',
            color: '#32afa4',
            textTransform: 'uppercase',
            marginBottom: '16px'
          }}>
            api基本信息
          </h4>
          <ProFormText
            name="apiNameCn"
            width="lg"
            label="api中文名称"
            tooltip="api 中文名称2-255长度"
            placeholder="请输入中文名称"
            rules={[
              {required: true, message: '名称不能为空'},
              {min: 2, message: '名称长度不能小于2'},
              {max: 255, message: '名称长度最大不能超过255'}
            ]}
          />
          <ProFormText
            name="apiName"
            width="lg"
            label="api英文名称"
            //@ts-ignore
            size="middle"
            tooltip="最长为 25 位，用于生成唯一url"
            placeholder="请输入中文名称"
            rules={[
              {required: true, message: '名称不能为空'},
              {min: 2, message: '名称长度不能小于2'},
              {max: 25, message: '名称长度最大不能超过25'}
            ]}
          />
          <ProFormTextArea
            name="apiDesc"
            label="api描述"
            width="lg"
            placeholder="请输入备注"
          />
          <h4 style={{
            fontSize: '15px',
            fontWeight: 'bold',
            color: '#32afa4',
            textTransform: 'uppercase',
            marginBottom: '16px'
          }}>api参数</h4>
          <ProFormSelect
            label="请求方式"
            name="reqType"
            width="lg"
            initialValue="0"
            tooltip={"请求方式会影响参数携带方式"}
            options={[
              {
                value: '1',
                label: 'POST',
              },
              {value: '0', label: 'GET'},
            ]}
            rules={[
              {required: true, message: '请选择请求方式'},
            ]}
          />
          <ProFormText
            name="queryTimeOut"
            width="lg"
            addonAfter={"s"}
            label="api查询超时时间"
            tooltip="超过时间会按照预定方式返回"
            placeholder="请输入参数"
            rules={[
              {
                pattern: /^(0|[1-9][0-9]*)$/,
                message: '请输入正确的参数',
              }
            ]}
          />
          <h4 style={{
            fontSize: '15px',
            fontWeight: 'bold',
            color: '#32afa4',
            textTransform: 'uppercase',
            marginBottom: '16px'
          }}>安全与缓存策略</h4>
          <ProFormText
            name="reqLimit"
            width="lg"
            label="单用户每秒调用次数上限"
            //@ts-ignore
            size="middle"
            tooltip="限制单用户每秒调用次数,用助于提高系统的稳定性"
            placeholder="请输入参数"
            rules={[
              {
                required:true,
                message:'调用次数未填写上限'
              },
              {
                max:2,
                message:'数据过长'
              },
              {
                pattern: /^(0|[1-9][0-9]*)$/,
                message: '请输入正确的参数',
              }
            ]}
          />
          <ProFormRadio.Group
            name="isCache"
            label="是否缓存"
            tooltip={"缓存会提高响应速度"}
            initialValue={1}
            options={[
              {
                label: '是',
                value: '1',
              },
              {
                label: '否',
                value: '0',
              },
            ]}
            rules={[
              {required: true, message: '请选择请求方式'},
            ]}
          />
          <ProFormDependency name={['isCache']}>
            {({isCache}) => {
              // 当 isCache 的值为 '1' 时，渲染下一个组件
              return isCache === '1' ? (
                <ProFormRadio.Group
                  name="cacheExpiryPeriod"
                  label="缓存失效周期"
                  tooltip={"缓存会按照配置失效"}
                  initialValue={1}
                  options={[
                    {
                      label: '分',
                      value: '1',
                    },
                    {
                      label: '时',
                      value: '2',
                    },
                    {
                      label: '天',
                      value: '3',
                    },
                    {
                      label: '周',
                      value: '4',
                    },
                    {
                      label: '月',
                      value: '5',
                    },
                  ]}
                  rules={[
                    {required: true, message: '请选择请求方式'},
                  ]}
                />
              ) : null;
            }}
          </ProFormDependency>
          <ProFormDependency name={['isCache']}>
            {({isCache}) => {
              // 当 isCache 的值为 '1' 时，渲染下一个组件
              return isCache === '1' ? (
                <ProFormText
                  name="cacheExpiryDateCron"
                  width="lg"
                  label="缓存corn表达式"
                  //@ts-ignore
                  size="middle"
                  tooltip="缓存失效表达式正则,默认按照选择的单位时间失效"
                  placeholder="请输入corn表达式"
                  rules={[
                    {
                      pattern: /^(\*|([0-9]|[1-5][0-9])|([0-9]-[0-9])|(\*\/[0-9]+))(\s+(\*|([0-9]|[1-5][0-9])|([0-9]-[0-9])|(\*\/[0-9]+))){4}$/,
                      message: '请输入有效的 Cron 表达式',
                    }
                  ]}
                />
              ) : null;
            }}
          </ProFormDependency>
        </StepsForm.StepForm>
        {/*  --------------------------------------------------step two-----------------------------------------------------------*/}
        <StepsForm.StepForm
          name="time"
          title="api配置"
          onFinish={async (values) => {
            const formData = formRef.current?.getFieldsValue(true)
            console.log("formData===>", formData)
          }}
        >
          <ProForm.Group style={{marginBottom: '16px', display: 'flex', justifyContent: 'space-between'}}>
            <ProFormSelect
              name="datasourceId"
              label="数据源"
              width={"md"}
              options={datasourceList}
              onChange={async (value) => {
                // @ts-ignore
                setDatasourceId(value)
              }}
              rules={[
                {required: true, message: '请选择数据源'}
              ]}
            />
            <ProFormSelect
              name="databaseName"
              label="数据库"
              width={"md"}
              options={databaseList}
              onChange={async (value) => {
                // @ts-ignore
                setDatabaseName(value);
              }}
              rules={[
                {required: true, message: '请选择数据库'}
              ]}
            />
          </ProForm.Group>
          <SqlFunctionEditor setSql={setSql}/>
          <div style={{marginBottom: '20px',top:'20px'}}>
            <ConfigSqlInputParam
              inputParams={configInputParam}
              //@ts-ignore
              setInputParams={setConfigInputParams}/>
          </div>
          <ProFormRadio.Group
            name="allowPaging"
            label="是否分页"
            tooltip={"数据量较大可选择"}
            initialValue={0}
            options={[
              {
                label: '是',
                value: '1',
              },
              {
                label: '否',
                value: '0',
              },
            ]}
            rules={[
              {required: true, message: '请选择是否分页'},
            ]}
          />
          <ProFormDependency name={['allowPaging']}>
            {({allowPaging}) => {
              // 当 isCache 的值为 '1' 时，渲染下一个组件
              return allowPaging === '1' ? (
                <ProFormText
                  name="respPageSize"
                  width="lg"
                  label="分页大小"
                  //@ts-ignore
                  size="middle"
                  tooltip="每页的数据量>=10"
                  placeholder="请输入corn表达式"
                  rules={[
                    {
                      pattern: /^(?:[1-9]\d{1,}|10)$/,
                      message: '请填写正确的分页参数，不能小于10',
                    }
                  ]}
                />
              ) : null;
            }}
          </ProFormDependency>
        </StepsForm.StepForm>
      </StepsForm>
    </>
  )
};

export default AddConfigSqlInterface;
